import React, { useContext, useEffect, useState } from "react";
import CreateIncludeNsTree from "@pkgs/Layout/CreateIncludeNsTree";
import { NsTreeContext } from "@pkgs/Layout/Provider";
import { FormattedMessage } from "react-intl";
import { Divider, Form, message, Popconfirm, Table } from "antd";
import _ from "lodash";
import moment from "moment";
import request from "@pkgs/request";
import api from "@common/api";
import DiscoveryMenu from "./common/DiscoveryMenu";
import type { ColumnProps } from "antd/lib/table";
import { Link } from "react-router-dom";
import BatchOperate from "./common/BatchOperate";
import { useAntdTable } from "@umijs/hooks";
import type { DiscoveryTableListType } from "./interface";
import "./style.less";

const Discovery: React.FC = (props) => {
  const nstreeContext = useContext(NsTreeContext);
  const nid = _.get(nstreeContext, "data.selectedNode.id");
  const type = _.get(props, "match.params.type");
  const discoveryType = type ? type : "stree";
  const { tableProps, refresh } = useAntdTable(() => getTableLists(), [nid, discoveryType]);
  const [selectedIds, setSelectedIds] = useState([] as any[]);
  const [selectedRows, setSelectedRows] = useState<DiscoveryTableListType[]>([]);
  const [testResultData, setTestResultData] = useState()

  /**
   * @func 获取发现规则列表
   */
  async function getTableLists() {
    try {
      const res: DiscoveryTableListType[] = await request(
        `${api.discovery}/list?type=${discoveryType}&nid=${nid}&watch_range=review`
      );
      const resData = res.map((item, index) => Object.assign(item,{ key: index }));
      return { data: resData }
    } catch (e) {
      (e + '').indexOf('null') ? 
      message.error('暂无数据!') :
      message.error('请求错误!')
      return { data: [] }
    }
  };

  /**
   * @func 删除发现规则
   * @param type
   * @param ids
   */
  const deleteList = async (type: string, ids: number[]) => {
    const data = JSON.stringify([
      {
        type: type,
        ids: ids,
      },
    ]);
    try {
      await request(api.discovery, { method: "DElETE", body: data });
      await getTableLists();
      refresh()
      message.success('删除成功!');
    } catch (e) {
      refresh()
      message.error('删除失败!');
    }
  };

  const testResult = (args: any) => {
    const { id, name, idc, port, type, nid, metrics_path } = args
    request(
      `${api.target}?id=${id}&name=${name}&port=${port}&idc=${idc}&type=${type}&nid=${nid}&metrics_path=${metrics_path}`
      ).then(res => {
        setTestResultData(res)
      }).catch(err => {
        message.error('请求错误！')
      })
  }

  useEffect(() => {
    refresh()
    setSelectedIds([])
    setSelectedRows([])
  }, []);

  useEffect(() => {
    refresh()
    setSelectedIds([])
    setSelectedRows([])
  }, [discoveryType, nid]);

  const Result = (props: any) => {
    return(
      <a onClick={() => {
        testResult(props)
      }}>
          检查结果
      </a>
  )}

  const columns: ColumnProps<DiscoveryTableListType>[] = [
    {
      title: "ID",
      dataIndex: "id",
      width: 70
    },
    {
      title: "服务名称",
      dataIndex: "name",
      width: 150
    },
    {
      title: "归属节点",
      dataIndex: "nid",
      width: 260,
      render: (text, record) => {
        const { treeData } = nstreeContext.data;
        const nodePath = _.get(_.find(treeData, { id: record.nid }), 'path');
        return <div>{nodePath}</div>
      },
    },
    {
      title: "监控端口",
      dataIndex: "port",
      width: 100
    },
    {
      title: "监控路径",
      dataIndex: "metrics_path",
      width: 120
    },
    {
      title: "修改人",
      dataIndex: "last_updator",
      width: 100
    },
    {
      title: "修改时间",
      dataIndex: "last_updated",
      width: 200,
      render: (text, record) => {
        return moment(text).format('YYYY-MM-DD HH:mm:ss');
      },
    },
    {
      title: "操作",
      fixed: 'right',
      render: (text, record) => {
        const { id, name, port, idc, type, nid, metrics_path } = record
        return (
          <span>
            <Link to={{
              pathname: `/prometheus/discovery/modify/${discoveryType}/${record.id}`,
              search: window.location.search ? window.location.search : `?nid=${nid}`
                }}
              >
                修改
            </Link>
            <Divider type="vertical" />
            <Link to={{
              pathname: `/prometheus/discovery/clone/${discoveryType}/${record.id}`,
              search: window.location.search ? window.location.search : `?nid=${nid}`
                }}
              >
                克隆
            </Link>
            <Divider type="vertical" />
            <Popconfirm
              title={<FormattedMessage id="table.delete.sure" />}
              onConfirm={() => { 
                deleteList(discoveryType, [id]); 
              }}
            >
              <a>删除</a>
              <Divider type="vertical" />
            </Popconfirm>
            <Result id={id} name={name} nid={nid} type={type} port={port} idc={idc} metrics_path={metrics_path} />
          </span>
        );
      },
    },
  ];

  const collectPathItem: ColumnProps<DiscoveryTableListType> = {
    title: "采集节点",
    dataIndex: "collect_path",
    width: 260
  }
  
  const lvsItem: ColumnProps<DiscoveryTableListType>[] = [
    {
      title: "机房",
      dataIndex: "idc"
    },{
      title: "VIP:PORT",
      dataIndex: "path"
    }
  ]

  const machinesItem: ColumnProps<DiscoveryTableListType> = {
    title: "主机列表",
    dataIndex: "machines",
    render: (text, record) => {
      const data = text?.split("\n")
      return data?.map((item: string, index: number) => (<div key={index}>{item}</div>))
    }
  }

  const urlItem: ColumnProps<DiscoveryTableListType>[] = [
    {
      title: "机房",
      dataIndex: "idc"
    },{
      title: "发现url",
      dataIndex: "url",
      width: 220
    }
  ]

  const startkItem: ColumnProps<DiscoveryTableListType>[] = [{
    title: "deployment",
    dataIndex: "deployment"
  }, {
    title: "容器集群",
    dataIndex: "cluster"
  }]

  if (discoveryType == 'stree') {
    columns.splice(3, 0, collectPathItem)
  }

  if (discoveryType == 'lvs') {
    columns.splice(3, 0, ...lvsItem)
  }

  if (discoveryType == 'manual') {
    columns.splice(3, 0, machinesItem)
  }

  if (discoveryType == 'stark') {
    columns.splice(3, 0, ...startkItem)
  }

  if (discoveryType == 'url') {
    columns.splice(3, 0, ...urlItem)
  }

  return (
    <div>
      <div className="discover_menu">
        <DiscoveryMenu {...props} />
        <BatchOperate 
          selectedData={selectedRows} 
          type={discoveryType} 
          deleteList={deleteList}
          refresh={refresh}
          setSelectedRows={setSelectedRows}
          setSelectedIds={setSelectedIds}
          />
      </div>
      
      <div style={{margin: '15px auto'}}>
        <Table         
          rowSelection={{
            selectedRowKeys: selectedIds,
            onChange: (selectedRowKeys: string[] | number[], selectedRows: DiscoveryTableListType[]) => {
              setSelectedIds(selectedRowKeys);
              setSelectedRows(selectedRows)
            }
          }}
          columns={columns}
          {...tableProps} 
          pagination={{
            showQuickJumper: true,
            showSizeChanger: true,
            pageSizeOptions: ["5", "10", "20", "30", "40", "50", "100"],
            defaultPageSize: 10,
          }}
          scroll={{ x: 1600 }}
        />
      </div>
      
    </div>
  );
};

export default CreateIncludeNsTree(Form.create()(Discovery), {
  visible: true,
});
